package com.gp.ssmplus.base.core.mybatis.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gp.ssmplus.base.core.mybatis.common.utils.ApiAssert;
import com.gp.ssmplus.base.core.mybatis.common.utils.FlymeUtils;
import com.gp.ssmplus.base.core.mybatis.common.utils.JsonUtils;
import com.gp.ssmplus.base.core.mybatis.common.utils.ReflectionUtils;
import com.gp.ssmplus.base.core.mybatis.entity.EntityMap;
import com.gp.ssmplus.base.core.mybatis.model.DeleteModel;
import lombok.Data;

/**
 * @author Administrator
 */
@Data
public class CriteriaDelete<T> extends QueryWrapper<T> {
    private EntityMap requestMap = new EntityMap();
    /**
     * 扩展事件名称
     */
    private String handlerName;

    private Class cls;
    /**
     * 主键字段
     */
    private String idField;

    private DeleteModel model;
    /**
     * 是否使用逻辑删除(必须添加逻辑删除字段)
     */
    private Boolean logicalDelete = true;

    /**
     * 是否删除关联文件
     */
    private Boolean delFile = false;

    /**
     * 表名
     */
    private String tableName;

    public EntityMap getRequestMap() {
        return requestMap;
    }

    public void setRequestMap(EntityMap requestMap) {
        this.requestMap = requestMap;
    }

    public String getHandlerName() {
        return handlerName;
    }

    public void setHandlerName(String handlerName) {
        this.handlerName = handlerName;
    }

    public CriteriaDelete() {

    }

    public EntityMap put(String key, Object value) {
        this.requestMap.put(key, value);
        return this.requestMap;
    }

    public <T> T getParams(String key) {
        EntityMap entityMap = JsonUtils.jsonToBean(model.getParams(), EntityMap.class);
        if (FlymeUtils.isNotEmpty(entityMap)) {
            this.requestMap.putAll(entityMap);
        }
        return requestMap.get(key);
    }

    public CriteriaDelete(DeleteModel model, Class cls) {
        Long[] ids = model.getIds();
        this.model = model;
        this.cls = cls;
        this.handlerName = model.getHandlerName();
        this.idField = ReflectionUtils.getTableField(cls);
        this.tableName = ReflectionUtils.getTableName(cls);
        String params = model.getParams();
        if (FlymeUtils.isEmpty(ids) && FlymeUtils.isEmpty(params)) {
            ApiAssert.failure("参数不能为空");
        }
        if (FlymeUtils.isNotEmpty(params)) {
            this.setRequestMap(JsonUtils.jsonToBean(params, EntityMap.class));
        }
        //添加按主键删除
        if (FlymeUtils.isNotEmpty(ids)) {
            if (ids.length == 1) {
                this.eq(idField, ids[0]);
            } else {
                this.in(idField, ids);
            }
        } else {
            Long id = this.requestMap.getLong(idField);
            this.in(FlymeUtils.isNotEmpty(id), idField, id);
        }
    }

    public void setCount(int count) {
        if (count == 0) {
            this.setLogicalDelete(false);
        }
    }

}
